package com.gluxen.controller;

import java.util.*;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import com.gluxen.common.exception.BusinessException;
import com.gluxen.util.Ufn;
import com.gluxen.util.weixinUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.gluxen.common.constant.SystemConstant;
import com.gluxen.entity.Gift;
import com.gluxen.entity.OrderForm;
import com.gluxen.entity.User;
import com.gluxen.service.GiftService;
import com.gluxen.service.IGiftService;
import com.gluxen.service.OrderService;
import com.gluxen.service.UserService;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class GiftController extends BaseController{
	@Resource
  IGiftService giftService;
	@Resource
  OrderService orderService;
	@Resource
  UserService userService;
  
	/**
	 * 添加礼品项
	 * @param gift
	 * @return  OK
	 */
    @RequestMapping("gift_add.json")
	@ResponseBody
	public Map<String, Object> addGift(Gift gift) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("success", false);
		try {
			System.out.println("nickname:"+gift.getName());
			if(giftService.queryGiftbyname(gift.getName()).size()>0)
				map.put("msg","礼品已存在！");
			else {
				giftService.addGift(gift);
				map.put("success", true);
				map.put("msg", "添加成功");
			}
		} catch (Exception e) {
			e.printStackTrace();
			map.put("msg", "系统错误，请重新尝试");
		}
		return map;
	}
    
    /**
     * 删除礼品信息。
     * @param id
     * @param request
     * @return
     */
    @RequestMapping("gift_delete.json")
	@ResponseBody
	public Map<String, Object> deleteGift(int id, HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		Gift gift = giftService.queryGiftbyId(id);
		try {
			    giftService.deleteGift(gift);
				map.put("success", true);
				map.put("msg", "删除成功");
		} catch (Exception e) {
			e.printStackTrace();
			map.put("success", false);
			map.put("msg", "系统错误");
		}
		return map;
	}
    
	/**
	 * 更新Gift
	 * @param gift
	 * @return map 返回的更新后的信息OK
	 */
	@RequestMapping("gift_update.json")
	@ResponseBody
	public Map<String, Object> updateUser(Gift gift, HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("success", false);
		User u = (User)request.getSession().getAttribute(SystemConstant.CURRENT_USER);
		try {
			if(giftService.queryGiftbyId(gift.getId())==null){
				map.put("success", false);
				map.put("msg", "不存在这个礼品项");
		    }else if(gift.getId() != 1 || u.getId() == 1) {
				giftService.updateGift(gift);
				map.put("success", true);
				map.put("msg", "更新成功");
			} else
				map.put("msg", "您没有修改该用户的权限");
		} catch (Exception e) {
			e.printStackTrace();
			map.put("msg", "系统错误，请重新尝试");
		}
		return map;
	}
    /**
     * 兑换礼品
     * @param id
     * @param amount
     * @paramu_id
     * @param request
     * @return
     */
    @RequestMapping("gift_buy.json")
	@ResponseBody
	public Map<String, Object> buyGift(Integer id ,Integer amount,HttpServletRequest request) {
    	Map<String, Object> map = new HashMap<String, Object>();
    	Gift gift = giftService.queryGiftbyId(id);
    	User user= (User) request.getSession().getAttribute(SystemConstant.CURRENT_USER);
    	
		try {
			if(gift.getInventory()-amount<0){
				map.put("success", false);
			    map.put("msg", "库存不足！");
			}else if(user.getIntegration()<(gift.getIntegration()*amount)){
				map.put("success", false);
			    map.put("msg", "积分不足");
			}else{
				gift.setInventory(gift.getInventory()-amount);
				giftService.updateGift(gift);
				user.setIntegration(user.getIntegration()-gift.getIntegration()*amount);
				userService.updateUser(user);
				
				OrderForm order = new OrderForm();
		    	order.setAmount(amount);
		    	order.setGift(gift);
		    	order.setUser(user);
		    	orderService.add(order);
		    	
			    map.put("success", true);
				map.put("msg", "购买礼品成功");
			}
		} catch (Exception e) {
			e.printStackTrace();
			map.put("success", false);
			map.put("msg", "系统错误");
		}
		return map;
	}
 
    /**
	 * 查询所有礼品信息
	 * @param 
	 *
	 * @return ListVo 员工对象集合
	 */
//	@RequestMapping("gift_list.json")
//	@ResponseBody
//	public ModelAndView listGift(String code, HttpServletRequest req) {
///** 所有的gift信息 */
//		ModelAndView mav = new ModelAndView();
//		Map<String,Object> map = new HashMap<String,Object>();
//		String openId = null;
//		//String openId = weixinUtil.Get_Openid(code);
//		List<User> temp = null;
//
//		if(openId!=null){
//			String hql = "from User u where u.isDelete=0 and u.openID='"+openId+"'";
//			temp = (List<User>) userService.queryObjectList(hql);
//			if(temp.size()==0){
//				System.out.println("登录用户是未注册用户：");
//				req.getSession().setAttribute("openid",openId);
//			}else{//已注册用户进入系统，进入用户中心
//				User tempUser = temp.get(0);
//				List<Integer> roleIdList = (List<Integer>) userService.queryListByNavtiveSql("select FK_ROLE_ID from USER_ROLE where FK_USER_ID=" + tempUser.getId());
//				if(roleIdList == null || roleIdList.size() == 0)
//					throw new BusinessException("该用户未分配角色，暂时不能访问本系统！");
//				tempUser.setRoles(new HashSet<Integer>(roleIdList));
//
//				List<Integer> privList = (List<Integer>) userService.queryListByNavtiveSql("select PRIV_ID from ROLE_PRIV where FK_ROLE_ID in (" + Ufn.join(roleIdList.toArray()) + ")");
//				Set<Integer> privs = new HashSet<Integer>(privList);
//
//				tempUser.setPrivs(privs);
//				privs.add(0);
//				req.getSession().setAttribute(SystemConstant.CURRENT_USER,tempUser);
//			}
//		}
//
//		List<Gift> all = new ArrayList<Gift>();
//		try {
//			all = (List<Gift>) giftService.queryGift();
//			map.put("giftList", all);
//			map.put("success", true);
//			map.put("msg", "获取礼品列表成功");
//		} catch (Exception e) {
//			e.printStackTrace();
//			map.put("success", false);
//			map.put("msg", "系统错误，获取礼品列表失败");
//		}
//		mav.setViewName("redirect:/gift.do");
//		mav.addAllObjects(map);
//		return mav;
//	}
	/**
	 * 查询所有礼品信息
	 * @param
	 *   员工的登陆名，非必须参数
	 * @return ListVo 员工对象集合
	 */

	@RequestMapping("gift_list.json")
	@ResponseBody
	public Map<String, Object> listGift() {
		/** 所有的gift信息 */
		Map<String, Object> map = new HashMap<String, Object>();
		List<Gift> all = new ArrayList<Gift>();
		try {
			all = (List<Gift>) giftService.queryGift();
			map.put("giftList", all);
			map.put("success", true);
			map.put("msg", "获取礼品列表成功");
		} catch (Exception e) {
			e.printStackTrace();
			map.put("success", false);
			map.put("msg", "系统错误，获取礼品列表失败");
		}
		return map;
	}

}
